import { _decorator } from 'cc';
import { DIRECTION_ENUM, ENTITY_STATE_ENUM, EVENT_ENUM } from '../Enum';
import { EntiyManager } from './EnityManager';
import { EventManager } from '../RunTime/EventManager';
import { DataManager } from '../RunTime/DataManager';
import { TILE_HEIGHT, TILE_WEIGHT } from '../Scripts/Tile/TileItem';
import { IEntity } from '../Levels';
const { ccclass, property } = _decorator;


@ccclass('EnemyManager')
export class EnemyManager extends EntiyManager {

  id: number
  // 移动使用
  targetX: number = 0
  targetY: number = 0
  readonly speed: number = 0.1
  in_moving: boolean = false


  async init(param: IEntity){
    super.init(param)
    this.node.setPosition(this.x * TILE_WEIGHT - 1.5*TILE_WEIGHT, -this.y * TILE_HEIGHT + 1.5*TILE_HEIGHT)
    EventManager.getInstance().on(EVENT_ENUM.PLAYER_BORN, this.OnChangeDirection, this)
    EventManager.getInstance().on(EVENT_ENUM.PLAYER_MOVE_END, this.OnChangeDirection, this)
    EventManager.getInstance().on(EVENT_ENUM.PLAYER_ATTACK, this.OnDead, this)

  }

  onDestroy(): void {
      EventManager.getInstance().off(EVENT_ENUM.PLAYER_BORN, this.OnChangeDirection)
      EventManager.getInstance().off(EVENT_ENUM.PLAYER_MOVE_END, this.OnChangeDirection)
      EventManager.getInstance().off(EVENT_ENUM.PLAYER_ATTACK, this.OnDead)
  }

  OnChangeDirection(){
    if (this.state == ENTITY_STATE_ENUM.DEAD) {
      return
    }

    const {x, y} = DataManager.getInstance().player

    // 比较disX比disY小说明靠近 Y轴
    const disX = Math.abs(this.x - x)
    const disY = Math.abs(this.y - y)

    let direction: DIRECTION_ENUM
    // player在怪物左上角
    if (this.x >= x && this.y >= y) direction = disX < disY ? DIRECTION_ENUM.TOP : DIRECTION_ENUM.LEFT
    // 左下角
    else if (this.x >= x && this.y < y) direction = disX < disY ? DIRECTION_ENUM.BOTTOM : DIRECTION_ENUM.LEFT
    // 右上角
    else if (this.x < x && this.y >= y) direction = disX < disY ? DIRECTION_ENUM.TOP : DIRECTION_ENUM.RIGHT
    // 右下角
    else direction = disX < disY ? DIRECTION_ENUM.BOTTOM : DIRECTION_ENUM.RIGHT

    this.direction = direction

  }


  OnDead(id: number){
    if (this.isInState(ENTITY_STATE_ENUM.DEAD)) {
      return
    }
    if (id !== this.id) {
      return
    }

    this.state = ENTITY_STATE_ENUM.DEAD
    EventManager.getInstance().emit(EVENT_ENUM.ENEMY_DEAD)

  }






}
